<template>
  <div class="comments-container">
    <h3>发表评论</h3>
    <hr>
    <textarea name id placeholder maxlength="200" v-model="comment"></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>

    <div class="content" v-for="(item,i) in this.commentsList" :key="i">
      <div
        class="user"
      >第{{i+1}}楼&nbsp;&nbsp;&nbsp;&nbsp;用户：{{item.user_name}}&nbsp;&nbsp;&nbsp;&nbsp;发表时间：{{item.add_time|dataFormat}}</div>
      <div class="comments">{{item.content==='undefined'?'此用户很懒什么都没说':item.content}}</div>
    </div>

    <mt-button type="danger" size="large" plain @click="load">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
export default {
  created() {
    this.getComments();
  },
  data() {
    return {
      commentsList: [],
      pageindex: 1,
      comment: ""
    };
  },
  props: ["id"],
  methods: {
    getComments() {
      this.$http
        .get(`api/getcomments/${this.id}?pageindex=${this.pageindex}`)
        .then(data => {
          this.commentsList = this.commentsList.concat(data.body.message);
        });
    },
    load() {
      this.pageindex++;
      this.getComments();
    },
    postComment() {
      this.$http
        .post("api/postcomment/" + this.id, {
          content: this.comment.trim()
        })
        .then(data => {
          // 校验comment

          if (this.comment.trim().length === 0) {
            return Toast("请输入评论内容");
          }
          if (data.body.status === 0) {
            // 不从客户端直接刷新渲染了 直接从客户端渲染
            let cmt = {
              user_name: "时长两年半的练习生",
              add_time: Date.now(),
              content: this.comment
            };
            this.commentsList.unshift(cmt);
            this.comment = "";
          }
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.comments-container {
  h3 {
    font-size: 18px;
  }
  .user {
    background-color: #ccc;
    font-size: 12px;
    margin-top: 5px 0px;
  }
  textarea {
  }
  .content {
    margin: 5px auto;
    .user {
      margin: 5px 0px;
    }
    .comments {
      font-size: 12px;
      text-indent: 2em;
    }
  }
}
</style>
